package org.example.app.service;

import jakarta.transaction.Transactional;
import jakarta.validation.constraints.Email;
import org.example.app.model.User;
import org.example.app.repository.BookKeepRepository;
import org.example.app.repository.UserRepository;
import org.example.app.service.util.CodeUtil;
import org.example.app.service.util.EmailUtil;
import org.example.app.service.util.JwtUtil;
import org.example.app.service.util.MD5Util;
import org.example.app.web.vm.UserVm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;


@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private BookKeepService bookKeepService;
    @Autowired
    private BookKeepRepository bookKeepRepository;

    @Transactional
    public User create (UserVm userVm) {
        //用md5加密后再返回
        userVm.setPassword(MD5Util.getMD5(userVm.getPassword()));
        //返回
        return userRepository.save(new User(userVm));
    }
    @Transactional
    public User update(UserVm userVm,User user){
        user.setRealname(userVm.getRealname());
         userRepository.save(user);
         return user;
    }

    @Transactional
    public void delete(User user) {
        bookKeepRepository.deleteByUser(user);
        if( bookKeepRepository.findByUser(user) == null){
            throw new RuntimeException("账本删除失败");
        }
        userRepository.deleteById(user.getId());
    }
    @Transactional
    public void resetPassword(UserVm userVm,User user) {
        user.setPassword(MD5Util.getMD5(userVm.getPassword()));
        // 修改user的数据库密码
        userRepository.save(user);
    }

    public String emailCode(User user) {
        String emailCode = CodeUtil.generateCode();
        String email = user.getEmail();
        // 用于控制塔查看
//        System.out.println("emailCode:"+emailCode);

        String message = "用户"+ user.getUsername() +"你的验证码如下：" + emailCode;
        // 发送邮件
        try {
            EmailUtil.sendEmail(email,  "验证码", message);
//            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
//            System.err.println("邮件发送失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
        return emailCode;
    }
}
